package com.zt.controller;

import com.zt.dto.LoginRequest;
import com.zt.dto.UpdatePasswordRequest;
import com.zt.entity.Result;
import com.zt.pojo.Users;
import com.zt.service.UsersService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @PostMapping("/getCode")
    public Result getCode(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        return usersService.getCode(phone);
    }
    
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        return usersService.login(loginRequest);
    }
    
    @GetMapping("/refreshToken")
    public Result refreshToken(@RequestParam String refreshToken) {
        return usersService.refreshToken(refreshToken);
    }

    //    获取用户信息
    @GetMapping("/info/{id}")
    public Result getUserInfo(@PathVariable Long id) {
        return usersService.getUserInfo(id);
    }

    // 检查用户是否已设置密码
    @GetMapping("/password/check/{userId}")
    public Result checkUserPassword(@PathVariable Long userId) {
        return usersService.checkUserPassword(userId);
    }

    // 修改用户密码，设置默认密码
    @PostMapping("/password/set")
    public Result setPassword(@RequestBody UpdatePasswordRequest updatePasswordRequest) {
        return usersService.updatePassword(updatePasswordRequest);
    }

     // 修改用
    //{newPassword: "w123456", oldPassword: "w123456"}
    @PutMapping("/password/update")
    public Result updatePassword(@RequestBody UpdatePasswordRequest updatePasswordRequest) {
        return usersService.updatePassword(updatePasswordRequest);
    }



    //    获取轮播图
    @GetMapping("/banner")
    public Result getBanner() {
        return usersService.getBanner();
    }

    // 修改用户的角色信息
    /**
     * 修改用户角色
     * @param roleInfo 包含userId和role的参数
     * @return 操作结果
     */
    @PostMapping("/updateRole")
    public Result updateUserRole(@RequestBody Map<String, Object> roleInfo) {
        System.out.println("修改用户角色，参数：" + roleInfo);
        
        // 获取参数
        Integer userId = null;
        Integer role = null;
        
        try {
            // 提取userId
            if (roleInfo.containsKey("userId")) {
                userId = Integer.valueOf(roleInfo.get("userId").toString());
            }
            
            // 提取role
            if (roleInfo.containsKey("role")) {
                role = Integer.valueOf(roleInfo.get("role").toString());
            }
            
            // 参数校验
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }
            
            if (role == null) {
                return Result.error("角色不能为空");
            }
            
            // 调用服务更新角色
            return usersService.updateUserRole(userId, role);
        } catch (Exception e) {
            System.out.println("修改用户角色异常：" + e.getMessage());
            e.printStackTrace();
            return Result.error("修改用户角色失败：" + e.getMessage());
        }
    }


    @Autowired
    private MinioClient minioClient;

    // 上传用户头像 todo
    @RequestMapping("/upload/avatar")
    @SneakyThrows
    public Result uploadAvatar(MultipartFile file) {
        if (file==null){
            return Result.error("请选择文件");
        }
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket("teacher-manager-user-avatar")
                .object(UUID.randomUUID().toString())
                .contentType("image/png")
                .stream(file.getInputStream(), file.getSize(), -1)
                .build();
        minioClient.putObject(putObjectArgs);
        return Result.success("上传成功", minioClient.getObjectUrl("teacher-manager-user-avatar", putObjectArgs.object()));
    }
    // 更改用户信息 todo
    @PutMapping("update/userbasic")
    public Result updateUserBasic(@RequestBody Map<String, Object> userInfo) {
        System.out.println("修改用户信息，参数：" + userInfo);

        // 获取参数
        Integer id = null;
        String nickname = null;
        String avatarUrl = null;

        try {
            if (userInfo.containsKey("id")) {
                id = Optional.ofNullable(userInfo.get("id"))
                        .map(Object::toString)
                        .map(Integer::valueOf)
                        .orElseThrow(() -> new IllegalArgumentException("用户ID不能为空"));
            }

// 提取nickname
            nickname = Optional.ofNullable(userInfo.get("nickname"))
                    .map(Object::toString)
                    .orElse(null); // 可以设置默认空字符串

// 提取avatarUrl
            avatarUrl = Optional.ofNullable(userInfo.get("avatarUrl"))
                    .map(Object::toString)
                    .orElse(null); // 可以设置默认头像URL
            Users users = new Users();
            users.setId(id);
            users.setNickname(nickname);
            users.setAvatarUrl(avatarUrl);
            boolean b = usersService.updateById(users);
            if (b){
                return Result.success("修改成功");
            }
            return Result.error("修改失败");

        }catch (Exception e){
            throw e;
        }

    }





}
